import { betterAuth } from "better-auth";
import { Pool } from "pg";

// 数据库连接配置
const pool = new Pool({
  host: process.env.DB_HOST || 'localhost',
  port: parseInt(process.env.DB_PORT || '5432'),
  user: process.env.DB_USER || 'postgres_user',
  password: process.env.DB_PASSWORD || 'postgres_pass',
  database: process.env.DB_NAME || 'fullstack_db',
  // 连接池配置
  max: 20,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
});

// 解析 ALLOWED_ORIGINS 环境变量
const getAllowedOrigins = (): string[] => {
  const origins = process.env.ALLOWED_ORIGINS || "http://localhost:3000";
  return origins.split(",").map(origin => origin.trim());
};

export const auth = betterAuth({
  database: pool,
  secret: process.env.BETTER_AUTH_SECRET!,
  baseURL: process.env.BETTER_AUTH_URL || "http://localhost:3000",
  
  // 启用邮箱密码登录
  emailAndPassword: {
    enabled: true,
    requireEmailVerification: false, // 开发环境关闭邮件验证，方便测试
  },
  
  // 会话配置
  session: {
    expiresIn: 60 * 60 * 24 * 7, // 7天过期
    updateAge: 60 * 60 * 24, // 1天更新一次
  },
  
  // 用户额外字段
  user: {
    additionalFields: {
      role: {
        type: "string",
        defaultValue: "user", // 默认角色是普通用户
      },
    },
  },
  
  // 使用环境变量的允许访问域名
  trustedOrigins: getAllowedOrigins(),
});